package com.chaoxin.lovehelp.controller;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.chaoxin.lovehelp.common.enums.SystemEnum;
import com.chaoxin.lovehelp.common.enums.vo.NewSessionVo;
import com.chaoxin.lovehelp.common.enums.vo.chatVo;
import com.chaoxin.lovehelp.common.utils.R;
import com.chaoxin.lovehelp.entity.FellowEntity;
import com.chaoxin.lovehelp.service.impl.AiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/ai")
public class AiController {

    @Autowired
    private AiService aiService;

    // 新建会话
    @PostMapping("/newsession")
    public ResponseBodyEmitter createSession(HttpServletRequest request,@RequestBody NewSessionVo userMessage) throws NoApiKeyException, InputRequiredException {
        // 0L 表示不超时，一直保持连接
        ResponseBodyEmitter emitter = new ResponseBodyEmitter(0L);

        // 异步执行流式调用，避免阻塞请求线程
        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                aiService.streamChat(request, userMessage.getUserMessage(), emitter);
                emitter.complete();       // 完成后关闭 SSE
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
        });

        return emitter;
    }

    // 发送用户消息
    /**
     * 接收前端 POST 请求，开启一个永不超时的 SseEmitter 流
     */
    @PostMapping(path = "/chat", produces =MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public ResponseBodyEmitter  chat(HttpServletRequest request, @RequestBody chatVo chatVo) {
        // 0L 表示不超时，一直保持连接
        ResponseBodyEmitter emitter = new ResponseBodyEmitter(0L);

        // 异步执行流式调用，避免阻塞请求线程
        Executors.newSingleThreadExecutor().submit(() -> {
            try {
                aiService.streamChat(request, chatVo.getUserMessage(), chatVo.getSessionId(), emitter);
                emitter.complete();       // 完成后关闭 SSE
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
        });

        return emitter;
    }

    // 查询单一会话聊天记录
    @GetMapping("/record/one")
    public R getChatRecords(HttpServletRequest request, @RequestParam String sessionId) {
        return aiService.getChatRecords(request,  sessionId);
    }

    //查询用户所有聊天会话以及返回每个会话第一个问题文本
    @GetMapping("/history")
    public R getHistory(HttpServletRequest request) {
        FellowEntity loginUser =(FellowEntity) request.getSession().getAttribute(SystemEnum.LOGIN_STATUS.getName());
        Long userId=Long.parseLong(loginUser.getId().toString());
        return R.ok().setData(aiService.getUserSessionList(userId));
    }

    // 删除单一会话聊天记录
    @DeleteMapping("/delete")
    public R deleteChatRecords(HttpServletRequest request, @RequestParam String sessionId) {
        return aiService.deleteChatRecords(request, sessionId);
    }

    // 删除用户所有聊天会话记录
    @DeleteMapping("/deleteall")
    public R deleteAllUserChatRecords(@RequestParam Long userId) {
        return aiService.deleteAllUserChatRecords(userId);
    }
}
